package com.spring.cold.common;

import com.spring.cold.utils.IdUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.util.StringUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;

/**
 * @author jy
 * @date 2020-10-16
 */
public class EntityWrapper {
    /**
     * 请求地址初始化参数
     */
    public final static String PRIMARY_KEY = "id";
    public final static String IS_DELETED = "isDeleted";
    public final static String PAGE = "/page";
    public final static String NEW = "/new";
    public final static String LIST = "/list";
    public final static String DELETE = "/delete";
    public final static String DELETE_ID = "/delete/{id}";
    public final static String UPTATE = "/update";
    public final static String UPTATE_ID = "/update/{id}";
    public final static String SHOW_ID = "/show/{id}";

    /**
     * 用于向待包装的对象添加主键、操作人或操作时间等信息
     *
     * @param t 待包装的对象
     */
    public static <T> T wrap(T t) {
        if (t == null) {
            return null;
        }
        BaseEntity baseEntity = new BaseEntity();
        try {
            Object id = PropertyUtils.getProperty(t, PRIMARY_KEY);
            if (StringUtils.isEmpty(id)) {
                baseEntity.setId(IdUtils.uuid());
                baseEntity.setCreateDate(Calendar.getInstance().getTime());
                baseEntity.setIsDeleted(Status.ACTIVE.toString());
            } else {
                baseEntity.setId(String.valueOf(id));
                baseEntity.setUpdateDate(Calendar.getInstance().getTime());
                Object isDeleted = PropertyUtils.getProperty(t, IS_DELETED);
                if (isDeleted != null){
                    baseEntity.setIsDeleted(String.valueOf(isDeleted));
                }
            }
            PropertyUtils.copyProperties(t, baseEntity);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return t;
    }

    public enum Status {

        ACTIVE, DELETED;

        /**
         * 0 : false 正常 1 : true  刪除
         */
        @Override
        public String toString() {
            switch (this) {
                case ACTIVE:
                    return "0";
                case DELETED:
                    return "1";
                default:
                    return "0";
            }
        }
    }
}
